package com.cheng.oa.serviceImpl;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.cheng.oa.domain.TbSign;
import com.cheng.oa.mapper.TbSignMapper;
import com.cheng.oa.mapper.TbUserMapper;
import com.cheng.oa.service.SignService;
import com.cheng.oa.vo.PageBean;
import com.cheng.oa.vo.SingChart;
import com.cheng.utils.DateUtil;

@Service
public class SignServiceImpl implements SignService {

	@Autowired
	private TbUserMapper usermapper;
	@Autowired
	private TbSignMapper mapper;

	@Override
	public PageBean<TbSign> showAll(Integer pageNum, Integer pageSize, String startDate, String endDate) {
		PageBean<TbSign> pageBean = new PageBean<TbSign>();

		if (!startDate.equals("") && !endDate.equals("")) {
			String startDate1 = startDate + " 00:00:00";
			String endDate1 = endDate + " 23:59:59";
			/*
			 * Date startDate2 = DateUtil.getDateBystr3(startDate1); Date
			 * endDate2 = DateUtil.getDateBystr3(endDate1);
			 */
			System.out.println("---A-------");
			HashMap<String, Object> map = new HashMap<String, Object>();
			map.put("startTime", startDate1);
			map.put("endTime", endDate1);
			map.put("start", (pageNum - 1) * pageSize);
			map.put("end", pageSize);
			List<TbSign> signs = mapper.selectPageBeanByTime(map);
			if (signs != null && signs.size() > 0) {
				for (int i = 0; i < signs.size(); i++) {
					signs.get(i).setUser(usermapper.selectByPrimaryKey(signs.get(i).getUid()));
				}
			}

			int total = mapper.selectPageBeanByTimeCount(map);
			// int total = mapper.selectPageBeanByTimeCount(map).size();

			pageBean.setRows(signs);
			pageBean.setTotal(total);
			return pageBean;

		} else {
			System.out.println("-B------------");

			HashMap<String, Object> map = new HashMap<String, Object>();
			map.put("start", (pageNum - 1) * pageSize);
			map.put("end", pageSize);
			List<TbSign> signs = mapper.selectPageBean(map);

			for (int i = 0; i < signs.size(); i++) {
				signs.get(i).setUser(usermapper.selectByPrimaryKey(signs.get(i).getUid()));
			}
			Integer total = mapper.selectPageBeanCount(map);
			// Integer total = mapper.selectPageBeanCount(map).size();
			pageBean.setRows(signs);
			pageBean.setTotal(total);
			return pageBean;
		}

	}

	@Override
	public List<SingChart> findSignCharts(String beignday) {

		return mapper.findSignChart(beignday);

	}

	@Override
	public int addSigns(String uId) {
		// TODO Auto-generated method stub

		TbSign tbSign = new TbSign();
		Date currentDayStartTime = DateUtil.getCurrentDayStartTime();
		Date currentDayEndTime = DateUtil.getCurrentDayEndTime();
		SingChart singChart = new SingChart();
		singChart.setCurrentDayEndTime(currentDayEndTime);
		singChart.setCurrentDayStartTime(currentDayStartTime);
		singChart.setUid(Integer.valueOf(uId));
		int selectId = mapper.selectIdDate(singChart);
		if (selectId == 1) {
			return 2;
		} else {

			tbSign.setFlag(1);
			tbSign.setUid(Integer.parseInt(uId));
			tbSign.setCreatetime(DateUtil.getNowDate());
			return mapper.insert(tbSign);
		}

	}

	@Override
	public int decideSign(Date nowDate, String uid) {
		TbSign tbSign = new TbSign();
		tbSign.setUid(Integer.parseInt(uid));
		tbSign.setCreatetime(nowDate);
		return mapper.selectId(tbSign);
	}

	@Override
	public String createExcel(String startDate, String endDate, HttpServletRequest request) {
		List<TbSign> signs = new ArrayList<TbSign>();
		if (!startDate.equals("") && !endDate.equals("")) {
			String startDate1 = startDate + " 00:00:00";
			String endDate1 = endDate + " 23:59:59";
			/*
			 * Date startDate2 = DateUtil.getDateBystr3(startDate1); Date
			 * endDate2 = DateUtil.getDateBystr3(endDate1);
			 */
			System.out.println("---A-------");
			HashMap<String, Object> map = new HashMap<String, Object>();
			map.put("startTime", startDate1);
			map.put("endTime", endDate1);
			signs = mapper.selectCreateExcelTime(map);
		} else {
			System.out.println("-B------------");
			HashMap<String, Object> map = new HashMap<String, Object>();
			signs = mapper.selectCreateExcelTimeNo(map);

		}

		HSSFWorkbook book = new HSSFWorkbook();
		HSSFSheet sheet = book.createSheet();
		// 创建第一行
		HSSFRow firstRow = sheet.createRow(0);
		// 在第一行创建对应的单元格也就是表中的字段
		TbSign sign = signs.get(0);
		JSONObject json = (JSONObject) JSONObject.toJSON(sign);

		Set<String> keySet = json.keySet();
		int i = 0;
		Iterator<String> iterator = keySet.iterator();
		while (iterator.hasNext()) {
			String key = (String) iterator.next();
			firstRow.createCell(i).setCellValue(key);
			i++;
		}

		for (int j = 1; j < signs.size() + 1; j++) {
			HSSFRow createRow = sheet.createRow(j);
			TbSign sign2 = signs.get(j - 1);
			JSONObject json2 = (JSONObject) JSONObject.toJSON(sign2);
			// 把每一遍历出来的user对象都转换成json 对象 并获取对应的key 和value
			// 现在要对每一列 进行赋值
			Iterator<String> iterator2 = json2.keySet().iterator();
			int k = 0;
			while (iterator2.hasNext()) {
				String key = (String) iterator2.next();
				Object object = json2.get(key);
				HSSFCell createCell = createRow.createCell(k);
				if (object instanceof Date) {
					createCell.setCellValue((Date) object);
				} else if (object instanceof Integer) {
					createCell.setCellValue((Integer) (object));
				} else {
					createCell.setCellValue((String) object);
				}
				k++;
			}
		}

		// 将生成好的excle 文件 输出到某一路径下 供别人下载
		String realPath = request.getSession().getServletContext().getRealPath("/upload");
		File file = new File(realPath + "/" + File.separator + System.currentTimeMillis() + ".xls");
		try {
			if (!file.exists()) {
				file.createNewFile();
				FileOutputStream stream;
				stream = FileUtils.openOutputStream(file);
				book.write(stream);
				book.close();
				stream.flush();
				stream.close();
				return file.getName();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;

	}

}
